﻿using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
using AppAcc.Models;
using AppAcc.Views.DanhMuc;

namespace AppAcc.Views.KTTH
{
    public partial class FormChungTuTongHopThemMoi : DevComponents.DotNetBar.RibbonForm
    {
        private PhanMenKeToanEntities1 db = new PhanMenKeToanEntities1();
        private int indexrow = 0;
        private bool co = false;
        public FormChungTuTongHopThemMoi()
        {
            InitializeComponent();
        }
        #region Event
        private void CmsChenDong_Click(object sender, EventArgs e)
        {
            var dgwr = new DataGridViewRow();
            dgvChiTietChungTu.Rows.Insert(indexrow, dgwr);
        }
        private void CmsXoaDong_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in dgvChiTietChungTu.Rows)
            {
                if (!r.IsNewRow)
                {
                    dgvChiTietChungTu.Rows.RemoveAt(r.Index);
                }
            }
        }
        private void dgvChiTietChungTu_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right) return;
            var ht = dgvChiTietChungTu.HitTest(e.X, e.Y);
            var rowindex = ht.RowIndex;// get id chi tiet phieu tang tscd
            indexrow = rowindex;
            if (ht.ColumnIndex != -1 && ht.RowIndex != -1)
            {
                //New menu strip 
                var Menu = new ContextMenuStrip();
                var chen = new ToolStripMenuItem("Chèn (Ins)");//new button
                chen.MouseDown += new MouseEventHandler(CmsChenDong_Click);// add event to button
                var xoa = new ToolStripMenuItem("Xóa (Del)");
                xoa.MouseDown += new MouseEventHandler(CmsXoaDong_Click);
                Menu.Items.AddRange(new ToolStripItem[] { chen });//add button to menu strip
                Menu.Items.AddRange(new ToolStripItem[] { xoa });
                //add menu to datagridview
                dgvChiTietChungTu.ContextMenuStrip = Menu;
            }
            else
                dgvChiTietChungTu.ContextMenuStrip = null;
        }

        private void FormChungTuTongHopThemMoi_Load(object sender, EventArgs e)
        {
            GetMaChungTu();
            FillTaiKhoan();
            FillDataChungTu();
            co = true;
            Reset();
            KiemTra();
        }

        private void bttThemMoi_Click(object sender, EventArgs e)
        {
            Reset();
            KiemTra();
        }

        private void bttLuu_Click(object sender, EventArgs e)
        {
            CreateChungTu();
        }

        private void bttLuu_Thoat_Click(object sender, EventArgs e)
        {
            CreateChungTu();
            this.Close();
        }

        private void bttLuu_ThemMoi_Click(object sender, EventArgs e)
        {
            CreateChungTu();
            Reset();
        }

        private void bttInChungTu_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Chua Code");
        }

        private void bttThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void cbbNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void cbbDoiTac_SelectedIndexChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void txtNoiDung_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }

        private void dtiNgayChungTu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dtiNgayLapPhieu_TextChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void cbbDoiTac_SelectedValueChanged(object sender, EventArgs e)
        {
            KiemTra();
        }
        private void dgvChiTietChungTu_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (co == true)
            {
                KiemTra();
                UpdateAmount(e.ColumnIndex);
                MessageBox.Show(e.ColumnIndex.ToString());
            }

        }
        private void bttThemMoiNhaCungCap_Click(object sender, EventArgs e)
        {
            var f = new FormDoiTac();
            f.ShowDialog();
        }

        private void bttThemMoiNhanVien_Click(object sender, EventArgs e)
        {
            var f = new FormNhanVien();
            f.ShowDialog();
        }
        private void cbbNhomNhaCungCap_SelectedIndexChanged(object sender, EventArgs e)
        {
            var index = Convert.ToInt32(cbbNhomNhaCungCap.SelectedIndex);
            if (index < 1) return;
            var id = Convert.ToInt32(cbbNhomNhaCungCap.SelectedValue);
            cbbDoiTac.DataSource = db.DoiTacs.Where(t => t.NhomDoiTacId == id).ToList();
            cbbDoiTac.DisplayMember = "TenDoiTac";
            cbbDoiTac.ValueMember = "Id";
            cbbDoiTac.SelectedIndex = -1;
            cbbDoiTac.Enabled = true;
        }


        #endregion Event
        #region Metho

        void GetMaChungTu()
        {
            var i = db.ChungTus.Count(t => t.TrangThai == 9);
            txtSoChungTu.Text = "CTTH" + (i + 1).ToString();
            txtSoChungTu.Enabled = false;
            dtiNgayChungTu.Value = DateTime.Now;
            dtiNgayLapPhieu.Value = DateTime.Now;
        }

        void FillTaiKhoan()
        {
            var n = dgvChiTietChungTu.Columns["TaiKhoanNo"] as DataGridViewComboBoxColumn;
            if (n != null)
            {
                n.DataSource = db.TaiKhoans.ToList();
                n.DisplayMember = "Id";
                n.ValueMember = "Id";
            }

            var c = dgvChiTietChungTu.Columns["TaiKhoanCo"] as DataGridViewComboBoxColumn;
            if (c == null) return;
            c.DataSource = db.TaiKhoans.ToList();
            c.DisplayMember = "Id";
            c.ValueMember = "Id";
        }
        void FillDataChungTu()
        {
            cbbNhanVien.DataSource = db.NhanViens.ToList();
            cbbNhanVien.DisplayMember = "TenNhanVien";
            cbbNhanVien.ValueMember = "Id";

            cbbNhomNhaCungCap.DataSource = db.NhomDoiTacs.ToList();
            cbbNhomNhaCungCap.DisplayMember = "TenNhomDoiTac";
            cbbNhomNhaCungCap.ValueMember = "Id";
            cbbNhomNhaCungCap.SelectedIndex = 0;

            cbbDoiTac.Enabled = false;
        }
        void KiemTra()
        {
            if (co == true)
            {
                if (txtNoiDung.Text != "" && Convert.ToInt32(cbbDoiTac.SelectedValue) != 0 && Convert.ToInt32(cbbNhanVien.SelectedValue) != 0 && dgvChiTietChungTu.RowCount > 1 && dtiNgayChungTu.Value.ToString().Length > 0 && dtiNgayLapPhieu.Value.ToString().Length > 0)
                {
                    bttInChungTu.Enabled = true;
                    bttLuu.Enabled = true;
                    bttLuu_ThemMoi.Enabled = true;
                    bttLuu_Thoat.Enabled = true;
                }
                else
                {
                    bttInChungTu.Enabled = false;
                    bttLuu.Enabled = false;
                    bttLuu_ThemMoi.Enabled = false;
                    bttLuu_Thoat.Enabled = false;
                }
            }
        }
        void Reset()
        {
            txtNoiDung.Text = "";
            GetMaChungTu();
            cbbDoiTac.SelectedIndex = -1;
            cbbNhanVien.SelectedIndex = -1;
            if (dgvChiTietChungTu.DataSource != null)
            {
                dgvChiTietChungTu.DataSource = null;
            }
            else
            {
                dgvChiTietChungTu.Rows.Clear();
            }
        }

        void CreateChungTu()
        {
            var pt = new ChungTu();
            pt.Id = txtSoChungTu.Text;
            pt.NgayChungTu = dtiNgayChungTu.Value;
            pt.NgayLapPhieu = dtiNgayLapPhieu.Value;
            pt.SoChungTuGoc = txtChungTuGoc.Text;
            pt.DoiTacId = Convert.ToInt32(cbbDoiTac.SelectedValue);
            pt.NhanVienId = Convert.ToInt32(cbbNhanVien.SelectedValue);
            pt.NoiDung = txtNoiDung.Text;
            pt.TrangThai = 9;
            var co = 0;//Phieu thu
            decimal soTienNo = 0;
            decimal soTienCo = 0;
            pt.TongTien = 0;
            foreach (DataGridViewRow item in dgvChiTietChungTu.Rows)
            {
                if (co < dgvChiTietChungTu.RowCount - 1)
                {
                    var ct = new ChungTuChiTiet();
                    ct.ChungTuId = pt.Id;

                    if (item.Cells["TaiKhoanNo"].Value != null && item.Cells["TaiKhoanNo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanNo = item.Cells["TaiKhoanNo"].Value.ToString();
                    }
                    else if (item.Cells["TaiKhoanCo"].Value != null && item.Cells["TaiKhoanCo"].Value.ToString().Length > 0)
                    {
                        ct.TaiKhoanCo = item.Cells["TaiKhoanCo"].Value.ToString();
                    }
                    if (item.Cells["SoTien"].Value != null && item.Cells["SoTien"].Value.ToString().Length > 0)
                    {
                        ct.SoTien = Convert.ToInt32(item.Cells["SoTien"].Value);
                    }
                    else
                    {
                        ct.SoTien = null;
                    }
                    if (item.Cells["DienGiai"].Value != null && item.Cells["DienGiai"].Value.ToString().Length > 0)
                    {
                        ct.DienGiai = item.Cells["DienGiai"].Value.ToString();
                    }
                    else
                    {
                        ct.DienGiai = null;
                    }
                    if (ct.TaiKhoanNo != null)
                    {
                        soTienNo += Convert.ToDecimal(ct.SoTien);
                    }
                    else if (ct.TaiKhoanCo != null)
                    {
                        soTienCo += Convert.ToDecimal(ct.SoTien);
                    }
                    co++;
                    db.ChungTuChiTiets.Add(ct);
                }
            }
            pt.TongTien += soTienCo;
            if (soTienCo != soTienNo)
            {
                MessageBox.Show("Số phát sinh Nợ phải bằng số phát sinh Có.");
                return;
            }
            db.ChungTus.Add(pt);
            try
            {
                db.SaveChanges();
                MessageBox.Show("Thêm mới thành công!");
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        private void UpdateAmount(int index)
        {
            int counter;
            for (counter = 0; counter < (dgvChiTietChungTu.Rows.Count - 1); counter++)
            {
                //kiem tra bay loi
                if (dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value != null || dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value != null)
                {
                    var tkNo = Convert.ToInt32(dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value);
                    var tkCo = Convert.ToInt32(dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value);

                    if (tkNo > 0 && tkCo > 0)
                    {
                        if (index == 0)
                        {
                            MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                            dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanNo"].Value = null;
                        }
                        else if(index == 1)
                        {
                            MessageBox.Show("Dữ liệu nhập không hợp lệ! Bạn chỉ co thể chọn 1 bên Nợ hoặc Có.");
                            dgvChiTietChungTu.Rows[counter].Cells["TaiKhoanCo"].Value = null;
                        }
                    }
                }
            }
        }
        #endregion Metho
    }
}